<?php

Class ShopManager
{
    private $_pk = 'shop_id';

    private $_dbStruct = array(
        'MAIN'  => array(
            'table'  => 'shop',
            'fields' => array('city_id', 'area_id', 'shop_type', 'name', 'alias_name', 'status', 'address', 'telphone', 'delivery_desc', 'delivery_time', 'min_charge', 'min_order', 'speed_avg', 'longitude', 'latitude', 'star', 'views', 'likes', 'picture', 'ordnum', 'tags', 'owner_uid', 'create_dt', 'update_dt', 'create_uid', 'update_uid'),
        ),
        'EXTRA' => array(
            'table'  => 'shop_extra',
            'fields' => array('contact', 'mobile', 'seo_title', 'seo_keywords', 'seo_description', 'memo', 'license', 'license_name', 'traffic', 'header_image', 'header_color', 'dna'),
        ),
    );

    private $_table = array();

    private $_db = array();

    private $shop_id = 0;

    public function __construct() {
        foreach($this->_dbStruct as $key => $var) {
            foreach($var['fields'] as $field)
                $this->_table[$field] = $key;
        }
    }

    public function getData($types = '') {
        $types = empty($types) ? array_keys($this->_dbStruct) : split(',', $types);
        $data = array();
        foreach($types as $type) {
            $arr = $this->getTable($type)->get($this->shop_id);
            if($arr)
                $data += $arr;
        }
        return $data;
    }

    public function setShopId($id) {
        $this->shop_id = intval($id);
        $this->setField('shop_id', $this->shop_id);
        return $this;
    }

    public function setField($field, $val) {
        $field = strtolower($field);
        if(isset($this->_table[$field])) {
            $type = $this->_table[$field];
            $this->getTable($type)->set($field, $val);
        }
        return $this;
    }

    public function reset() {
        $this->_db = array();
        return $this;
    }

    public function updateDb() {
        $types = array_keys($this->_db);
        foreach($types as $type) {
            $this->getTable($type)->update($this->shop_id);
        }
    }

    public function insertDb() {
        $types = array_keys($this->_db);
        foreach($types as $type) {
            if($this->shop_id)
                $this->getTable($type)->set($this->_pk, $this->shop_id)->insert();
            else
                $this->getTable($type)->insert();
        }
    }

    public function getTable($type) {
        if(isset($this->_dbStruct[$type])) {
            isset($this->_db[$type]) or
                $this->_db[$type] = new DbTable($this->_dbStruct[$type]['table'],  array($this->_pk, $this->_dbStruct[$type]['fields']));
            return $this->_db[$type];
        }else{
            throw new Exception('No this type');
        }
    }
}
